﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AssetManagementSystem.View;
using System.Data;

using AssetManagementSystem.Utils;
using AssetManagementSystem.Model;
using AssetManagementSystem.View.Controls;

namespace AssetManagementSystem.Presenter {
    class PresenterMain : ApplicationContext {
        
        //counts the number of open forms, if it reaches zero, application should exit.
        int formCount;

        //Create a new laucher ui and wait for a database to be selected
        public PresenterMain() {
            UILauncher uiLaunch = new UILauncher();
            uiLaunch.Open_Database += new EventHandler(SetApplicationDatabase);
            uiLaunch.FormClosed += new FormClosedEventHandler(OnFormClosed);
            FocusOnForm(uiLaunch);
            formCount++;
        }

        private void SetApplicationDatabase(object sender, EventArgs e) {
            UILauncher uiSender = (UILauncher)sender;
            uiSender.Hide();
            // Create an instance of the open file dialog box.
            OpenFileDialog openDatabaseFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openDatabaseFileDialog.Filter = GlobalConstants.DATABASE_TYPES;
            openDatabaseFileDialog.FilterIndex = 1;

            // Process input if the user clicked OK.
            if (openDatabaseFileDialog.ShowDialog() == DialogResult.OK) {
                //Set the database connection string for all DAOs
                DAOManager.SetDatabaseURI(openDatabaseFileDialog.FileName);

                //Create a new main ui and display it
                UIMain uiMain = new UIMain();
                uiMain.FormClosed += new FormClosedEventHandler(OnFormClosed);
                FocusOnForm(uiMain);
                formCount++;
                uiSender.Close();
            } else {
                //if the user did not select a database, return to the Launcher
                FocusOnForm(uiSender);
            }

        }

        private void OnFormClosed(object sender, EventArgs e) {
            // When a form is closed, decrement the count of open forms. 
            formCount--;
            // When the count gets to 0, exit the app by calling 
            // ExitThread().
            if (formCount == 0) {
                ExitThread();
            }
        }

        private void FocusOnForm(Form form) {
            form.Show();
            form.Activate();
        }
    }
}
